﻿using System;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Controls;
using Outlook.WorkItems.Extension.Manager.TeamProjectManager;
using Application = Microsoft.Office.Interop.Outlook.Application;
using Exception = System.Exception;

namespace Outlook.WorkItems.Extension.Addin
{
    partial class WorkItemFormRegion
    {
        #region Form Region Factory

        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Appointment)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Task)]
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
        [Microsoft.Office.Tools.Outlook.FormRegionName("Outlook.WorkItems.Extension.Addin.WorkItemFormRegion")]
        public partial class WorkItemFormRegionFactory
        {
            // Occurs before the form region is initialized.
            // To prevent the form region from appearing, set e.Cancel to true.
            // Use e.OutlookItem to get a reference to the current Outlook item.
            private void WorkItemFormRegionFactory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
            {
                dynamic item = e.OutlookItem;

                if (item == null)
                {
                    e.Cancel = true;
                    return;
                }

                //var inspec = item.GetInspector() as Inspector;
                //var explor = item.GetInspector() as Explorer;
                //if (inspec == Globals.ThisAddIn.Application.ActiveInspector()) // inspector
                //{
                    if (!Properties.Settings.Default.ShowWIInExplorer)
                    { 
                        e.Cancel = true;
                        return;
                    }
                //}
                //else
                //{
                //    if (!Properties.Settings.Default.ShowWIInExplorer)
                //    { 
                //        e.Cancel = true;
                //    return;
                //    }
                //}
                
                
                var mailItem = e.OutlookItem as MailItem;

                WorkItemStore store = null;

                var teamServer = item.ItemProperties["TeamServer"];

                if (teamServer != null && !string.IsNullOrEmpty(teamServer.Value.ToString()))
                {
                    var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamServer.Value.ToString()));
                    store = tfs.GetService<WorkItemStore>();
                }
                else
                {
                    var folder = item.ItemProperties.Parent.Parent as MAPIFolder;
                    if (folder != null && TeamProjectLinksManager.ContainsTeamProjectLink(folder.EntryID))
                    {
                        var link = TeamProjectLinksManager.GetTeamProjectLink(folder.EntryID);
                        var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(link.TeamServerUri));
                        store = tfs.GetService<WorkItemStore>();
                    }
                }

                if (store == null)
                {
                    e.Cancel = true;
                    return;
                }
                var relatedWorkItemsId = item.ItemProperties["RelatedWIIds"];
                if (relatedWorkItemsId == null || relatedWorkItemsId.Value == null || relatedWorkItemsId.Value == "")
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        #endregion

        private WorkItem _workItem;

        // Occurs before the form region is displayed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void WorkItemFormRegion_FormRegionShowing(object sender, System.EventArgs e)
        {
            dynamic item = this.OutlookItem;
            if (item == null)
                return;

            WorkItemStore store = null;
            
            var teamServer = item.ItemProperties["TeamServer"];

            if (teamServer != null && !string.IsNullOrEmpty(teamServer.Value.ToString()))
            {
                var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamServer.Value.ToString()));
                store = tfs.GetService<WorkItemStore>();
            }
            else
            {
                var folder = item.ItemProperties.Parent.Parent as MAPIFolder;
                if (folder != null && TeamProjectLinksManager.ContainsTeamProjectLink(folder.EntryID))
                {
                    var link = TeamProjectLinksManager.GetTeamProjectLink(folder.EntryID);
                    var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(link.TeamServerUri));
                    store = tfs.GetService<WorkItemStore>();
                }
            }

            if (store == null)
                return;

            var relatedWorkItemsId = item.ItemProperties["RelatedWIIds"];
            if (relatedWorkItemsId == null || relatedWorkItemsId.Value == null)
                return;

            var wiIds = relatedWorkItemsId.Value.ToString();
            var splittedIds = wiIds.Split(';');
            foreach (var wiId in splittedIds)
            {
                int id;
                if (Int32.TryParse(wiId, out id))
                {
                    _workItem = store.GetWorkItem(id);
                    break;
                }
            }
            var frm = new WorkItemFormControl
            {
                FormDefinition = _workItem.DisplayForm,
                Item = _workItem,
                ReadOnly = true
            };

            panel1.Controls.Add(frm);
            frm.Dock = DockStyle.Fill;
        }

        // Occurs when the form region is closed.
        // Use this.OutlookItem to get a reference to the current Outlook item.
        // Use this.OutlookFormRegion to get a reference to the form region.
        private void WorkItemFormRegion_FormRegionClosed(object sender, System.EventArgs e)
        {
            try
            {
                panel1.Controls.Clear();
                _workItem = null;
            }
            catch{}
            

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (_workItem != null)
                _workItem.Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            _workItem.Reset();
        }
    }
}
